package com.banmao;

import cn.hutool.core.io.FileUtil;
import com.banmao.util.RetryUtil;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

@Data
@Slf4j
@Builder
public class XManPage implements Runnable {

    //private File chapterFile;
    //
    //private String chapterCode;
    //
    //private String chapterTitle;

    //private Integer pages;

    private Integer pageIndex;

    //private HashMap<String, String> cookies;

    private XManChapter xManChapter;

    public Boolean getChapterImageByIndex() {

        boolean exist = FileUtil.exist(xManChapter.getChapterFile().getAbsolutePath() + File.separator + pageIndex + Constant.JPG);
        if (exist) {
            return true;
        }

        FakeBrowser fakeBrowser = FakeBrowser.builder()
                .host(Constant.HOST)
                .headers(Constant.BASE_HEADERS)
                .build();
        fakeBrowser.addHeader("referer", "https://" + Constant.HOST + "/" + xManChapter.getChapterCode());
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        /**
         * cid: XMANHUA_CID, page: XMANHUA_PAGE, key: mkey,
         * _cid: XMANHUA_CID, _mid: XMANHUA_MID, _dt: XMANHUA_VIEWSIGN_DT, _sign: XMANHUA_VIEWSIGN
         */
        //HashMap<String, String> cookies = COOKIES_THREADLOCAL.get();
        String XMANHUA_CID = xManChapter.getCookies().get("XMANHUA_CID");
        String XMANHUA_PAGE = xManChapter.getCookies().get("XMANHUA_PAGE");
        String mkey = xManChapter.getCookies().get("mkey");
        String XMANHUA_MID = xManChapter.getCookies().get("XMANHUA_MID");
        String XMANHUA_VIEWSIGN_DT = xManChapter.getCookies().get("XMANHUA_VIEWSIGN_DT");
        String XMANHUA_VIEWSIGN = xManChapter.getCookies().get("XMANHUA_VIEWSIGN");

        params.put("cid", XMANHUA_CID);
        params.put("page", String.valueOf(pageIndex));
        params.put("key", "");
        params.put("_cid", XMANHUA_CID);
        params.put("_mid", XMANHUA_MID);
        params.put("_dt", XMANHUA_VIEWSIGN_DT.replace(" ", "+").replace(":", "%3A"));
        params.put("_sign", XMANHUA_VIEWSIGN);

        //MANGABZ_MACHINEKEY=45dae9fd-c52a-4bdb-8bac-7efac8777211;
        //_ga_RV4ME3C1XE=GS1.1.1689410399.3.1.1689411367.0.0.0;
        //firsturl=https%3A%2F%2Fwww.xmanhua.com%2Fm8470%2F;
        //firsturl=https%3A%2F%2Fwww.xmanhua.com%2Fm8470%2F
        //fakeBrowser.addHeader("cookie", "MANGABZ_MACHINEKEY=45dae9fd-c52a-4bdb-8bac-7efac8777211; _ga_RV4ME3C1XE=GS1.1.1689410399.3.1.1689411367.0.0.0; firsturl=https%3A%2F%2Fwww.xmanhua.com%2Fm8470%2F; firsturl=https%3A%2F%2Fwww.xmanhua.com%2Fm8470%2F");

        String html = fakeBrowser.sendGet(xManChapter.getChapterCode() + "chapterimage.ashx", params);

        if (log.isDebugEnabled()) {
            log.debug("{}-{}, evalJS:{}", xManChapter.getChapterCode(), pageIndex, html);
        }

        try {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");

            ArrayList<String> imageUrlList = new ArrayList<>();
            ScriptObjectMirror obj = (ScriptObjectMirror) engine.eval(html);
            for (Map.Entry<String, Object> objectEntry : obj.entrySet()) {
                imageUrlList.add(String.valueOf(objectEntry.getValue()));
            }

            if (imageUrlList.size() >= 1) {
                downloadImagesPic(imageUrlList.get(0));
            }
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    private void downloadImagesPic(String imageUrl) {

        LinkedHashMap<String, String> imageHeaders = new LinkedHashMap<>();
        //"accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
        //"accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9",
        //"cache-control": "no-cache",
        //"pragma": "no-cache", "referer": "https://www.xmanhua.com/",
        //"sec-ch-ua": "'Not?A_Brand';v='8', 'Chromium';v='108', 'Google Chrome';v='108'",
        //"sec-ch-ua-mobile": "?0",
        //"sec-ch-ua-platform": "'Windows'", "sec-fetch-dest": "image", "sec-fetch-mode": "no-cors",
        //"sec-fetch-site": "same-site",
        imageHeaders.put("accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8");
        imageHeaders.put("accept-encoding", "gzip, deflate, br");
        imageHeaders.put("accept-language", "zh-CN,zh;q=0.9");
        imageHeaders.put("cache-control", "no-cache");
        imageHeaders.put("pragma", "no-cache");
        imageHeaders.put("referer", "https://www.xmanhua.com/");
        imageHeaders.put("sec-ch-ua", "'Not?A_Brand';v='8', 'Chromium';v='108', 'Google Chrome';v='108'");
        imageHeaders.put("sec-ch-ua-mobile", "?0");
        imageHeaders.put("sec-ch-ua-platform", "'Windows'");
        imageHeaders.put("sec-fetch-dest", "image");
        imageHeaders.put("sec-fetch-mode", "no-cors");
        imageHeaders.put("sec-fetch-site", "same-site");

        FakeBrowser fakeBrowser = FakeBrowser.builder()
                .host(Constant.HOST)
                .headers(imageHeaders)
                .build();
        //fakeBrowser.addHeader("referer", "https://" + HOST + "/");
        byte[] bytes = fakeBrowser.sendImageGet(imageUrl, null);
        if (bytes == null || bytes.length == 0) {
            log.error("图片获取失败");
            return;
        }
        handleImageFile(bytes);
    }


    // 保存二进制数据
    private void handleImageFile(byte[] bytes) {
        File file = FileUtil.touch(xManChapter.getChapterFile().getAbsolutePath() + File.separator + pageIndex + Constant.JPG);
        //try (FileOutputStream fos = new FileOutputStream(file)) {
        //    if (log.isDebugEnabled()) {
        //        log.debug("保存文件  {}", file.getAbsoluteFile());
        //    }
        //    fos.write(bytes);
        //    fos.flush();
        //} catch (Exception e) {
        //    throw new RuntimeException(e);
        //}
        FileUtil.writeBytes(bytes, file);
    }

    @Override
    public void run() {

        RetryUtil.RetryProperty<Object> property = RetryUtil.RetryProperty.builder()
                .maxAttempts(5)
                .waitDuration(Duration.ofSeconds(1))
                .retryOnException(throwable -> {
                    log.error("{} - {} 下载失败:{}", xManChapter.getChapterTitle(), pageIndex, throwable.getMessage());
                    return true;
                })
                .callable(this::getChapterImageByIndex).build();

        boolean success = false;
        try {
            success = (boolean) RetryUtil.retry(property);
        } catch (Exception e) {
            //throw new RuntimeException(e);
        } finally {
            synchronized (xManChapter.getChapter_countDownLatch()) {
                xManChapter.getChapter_countDownLatch().countDown();
                log.info("{} {} 进度: {} / {}", xManChapter.getChapterTitle(), (success ? "成功" : "失败"),
                        (xManChapter.getPages() - xManChapter.getChapter_countDownLatch().getCount()), xManChapter.getPages());
                if (!success) {
                    // 没有成功
                    this.xManChapter.getChapterSuccess().compareAndSet(true, false);
                }
            }
        }


    }
}
